/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */

package com.github.pig.admin.controller;


import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.feilong.core.DatePattern;
import com.feilong.core.date.DateUtil;
import com.github.pig.admin.model.entity.SysDict;
import com.github.pig.admin.service.SysDictService;
import com.github.pig.common.constant.CommonConstant;
import com.github.pig.common.util.ConvertMapUtil;
import com.github.pig.common.util.Query;
import com.github.pig.common.util.R;
import com.github.pig.common.util.UserUtils;
import com.github.pig.common.web.BaseController;
import com.xiaoleilu.hutool.date.DateUnit;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.validation.ValidationUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 字典表 前端控制器
 * </p>
 *
 * @author lengleng
 * @since 2017-11-19
 */
@Api(value = "DictController", description = "字典表")
@RestController
@RequestMapping("/dict" )
public class DictController extends BaseController {
    @Autowired
    private SysDictService sysDictService;

    /**
     * 通过ID查询字典信息
     *
     * @param id ID
     * @return 字典信息
     */
    @GetMapping("/{id}" )
    @ApiOperation(value = "  按id查询", httpMethod = "GET", notes = "  按id查询")
    public SysDict dict(@PathVariable String id) {
        return sysDictService.selectById(id);
    }

    /**
     * 分页查询字典信息
     *
     * @param params 分页对象
     * @return 分页对象
     */
    @RequestMapping("/dictPage" )
    @ApiOperation(value = "分页查询 参数为SysDict表中的属性",httpMethod = "GET", notes = "")
    public Page dictPage(@RequestParam Map<String, Object> params) {
        params.put(CommonConstant.DEL_FLAG, CommonConstant.STATUS_NORMAL);
        if (params.get("startTime") != null && params.get("endTime") != null) {
            Date startTime = DateUtil.toDate(params.get("startTime").toString(),DatePattern.COMMON_DATE);
            Date endTime = DateUtil.toDate(params.get("endTime").toString(),DatePattern.COMMON_DATE);
            params.remove("startTime");
            params.remove("endTime");

            return sysDictService.selectPage(new Query<>(ConvertMapUtil.convertMapOfUnderLine(params)),
                    Condition.create().between("create_time", startTime, endTime).orderBy("sort",true));
        }
            return sysDictService.selectPage(new Query<>(ConvertMapUtil.convertMapOfUnderLine(params)),
                    new EntityWrapper<>(new SysDict()).orderBy("sort",true));
    }


    /**
     * 查询字典信息
     *
     * @param params 分页对象
     * @return 分页对象
     */
    @RequestMapping("/dictList" )
    @ApiOperation(value = "查询 参数为SysDict表",httpMethod = "GET", notes = "")
    public List<SysDict> dictList(@RequestParam Map<String, Object> params) {
        params.put(CommonConstant.DEL_FLAG, CommonConstant.STATUS_NORMAL);
        params.put("limit",40);
        if (params.get("startTime") != null && params.get("endTime") != null&& params.get("label")!=null) {
            Date startTime = DateUtil.toDate(params.get("startTime").toString(),DatePattern.COMMON_DATE);
            Date endTime = DateUtil.toDate(params.get("endTime").toString(),DatePattern.COMMON_DATE);
            return sysDictService.selectList(Condition.create().eq("label",params.get("label"))
                    .between("create_time", startTime, endTime).orderBy("sort",true));
        }

        Page<SysDict> page= sysDictService.selectPage(new Query<>(ConvertMapUtil.convertMapOfUnderLine(params)),
                new EntityWrapper<>(new SysDict()).orderBy("sort",true));
        return page.getRecords();
    }


    /**
     * 通过字典类型查找字典
     *
     * @param type 类型
     * @return 同类型字典
     */
    @GetMapping("/type/{type}" )
    @ApiOperation(value = "通过字典类型查找字典参数为type",httpMethod = "GET", notes = "")
    @Cacheable(value = "dict_details", key = "#type" )
    public List<SysDict> findDictByType(@PathVariable String type) {
        SysDict condition = new SysDict();
        condition.setDelFlag(CommonConstant.STATUS_NORMAL);
        condition.setType(type);
        return sysDictService.selectList(new EntityWrapper<>(condition).orderBy("sort",true));
    }

    /**
     * 通过字典类型查找字典
     *
     * @param label 类型
     * @return 同类型字典
     */
    @GetMapping("/label/{label}" )
    @ApiOperation(value = "通过字典类型查找字典参数为label",httpMethod = "GET", notes = "")
    @Cacheable(value = "dict_details", key = "#label" )
    public List<SysDict> findDictByLabel(@PathVariable String label) {
        SysDict condition = new SysDict();
        condition.setDelFlag(CommonConstant.STATUS_NORMAL);
        condition.setType(label);
        return sysDictService.selectList(new EntityWrapper<>(condition).orderBy("sort",true));
    }

    /**
     * 添加字典
     *
     * @param sysDict 字典信息
     * @return success、false
     */
    @PostMapping
    @ApiOperation(value = "  添加数据 参数SysDict实体", httpMethod = "POST", notes = "  ")
    public R<Boolean> dict(@RequestBody SysDict sysDict) {
        sysDict.setCreator(UserUtils.getUser());
        sysDict.setCreateTime(new Date());
        sysDict.setDelFlag(CommonConstant.STATUS_NORMAL);
        System.out.println(sysDict.toString());
        return new R<>(sysDictService.insert(sysDict));
    }

    /**
     * 删除字典，并且清除字典缓存
     *
     * @param id   ID
     * @return R
     */
    @DeleteMapping("/{id}" )
    @ApiOperation(value = "按id删除", notes = "")
    public R<Boolean> deleteDict(@PathVariable String id) {
        return new R<>(sysDictService.deleteById(id));
    }

    /**
     * 修改字典
     *
     * @param sysDict 字典信息
     * @return success/false
     */
    @PutMapping
    @ApiOperation(value = "修改 参数SysDept实体", notes = "")
    public R<Boolean> editDict(@RequestBody SysDict sysDict) {
        return new R<>(sysDictService.updateById(sysDict));
    }
}
